package com.pactera.asmp.server.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @ProjectName: asmp_server
 * @Package com.pactera.asmp.server.config
 * @ClassName: ThreadPoolTaskExecutorConfig
 * @Description: ThreadPoolTaskExecutorConfig
 * @Date 2020/05/30 19:02
 * @Author lvzhiqiang
 * @Version 1.0
 */
@Configuration
@EnableAsync
public class ThreadPoolTaskExecutorConfig {
    @Value("${threadPoolTaskExecutor.corePoolSize}")
    private int corePoolSize;

    @Value("${threadPoolTaskExecutor.maxPoolSize}")
    private int maxPoolSize;

    @Value("${threadPoolTaskExecutor.queueCapacity}")
    private int queueCapacity;

    @Value("${threadPoolTaskExecutor.keepAliveSeconds}")
    private int keepAliveSeconds;


    @Bean
    public Executor asyncServiceExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        //最小线程数
        threadPoolTaskExecutor.setCorePoolSize(corePoolSize);
        //最大线程数
        threadPoolTaskExecutor.setMaxPoolSize(maxPoolSize);
        //等待队列
        threadPoolTaskExecutor.setQueueCapacity(queueCapacity);
        //线程池维护线程所允许的空闲时间
        threadPoolTaskExecutor.setKeepAliveSeconds(keepAliveSeconds);
        threadPoolTaskExecutor.setThreadNamePrefix("MyThreadPoolTaskExecutor-");

        // rejection-policy：当pool已经达到max size的时候，如何处理新任务
        // CALLER_RUNS：不在新线程中执行任务，而是由调用者所在的线程来执行
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }

    @Bean
    public Executor scheduledExecutor() {
        ScheduledThreadPoolExecutor scheduledThreadExecutor = new ScheduledThreadPoolExecutor(corePoolSize,new ThreadPoolExecutor.CallerRunsPolicy());
        return scheduledThreadExecutor;
    }
}
